package com.github.xuemingyu.springboot.jkfaststart.service.impl;

import com.bidanet.springmvc.demo.jkbuilder.JkVerifyUtils;
import com.github.xuemingyu.springboot.jkfaststart.controller.admin.view.user.AddAdminUser;
import com.github.xuemingyu.springboot.jkfaststart.domain.AdminUser;
import com.github.xuemingyu.springboot.jkfaststart.domain.type.Status;
import com.github.xuemingyu.springboot.jkfaststart.repository.AdminUserRepository;
import com.github.xuemingyu.springboot.jkfaststart.service.AdminUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AdminUserServiceImpl extends BaseServiceImpl<AdminUser, Long> implements AdminUserService {
    @Autowired
    AdminUserRepository adminUserRepository;

    @Override
    public void saveUser(AddAdminUser addAdminUser) {
        JkVerifyUtils.verify(addAdminUser);
        AdminUser adminUser = new AdminUser();
        if (Objects.isNull(addAdminUser.getId())) {
            addAdminUser.setPwd(DigestUtils.md5Hex(addAdminUser.getPwd()));
            adminUser.setDelete(false);
            adminUser.setStatus(Status.open);
            adminUser.setCreateTime(new DateTime());
        } else {
            adminUser = adminUserRepository.findOne(addAdminUser.getId());
            if (!adminUser.getPwd().equals(addAdminUser.getPwd())) {
                addAdminUser.setPwd(DigestUtils.md5Hex(addAdminUser.getPwd()));
            }
        }
        BeanUtils.copyProperties(addAdminUser, adminUser);
        adminUserRepository.save(adminUser);


    }

    @Override
    public void updatePwd(Long id, String pwd, String newPwd) {
        checkNull(id, "编号不能为空");
        checkString(pwd, "旧密码不能为空");
        checkString(newPwd, "新密码不能为空");
        AdminUser adminUser = adminUserRepository.findOne(id);
        if (!DigestUtils.md5Hex(pwd).equals(adminUser.getPwd())) {
            errorMsg("旧密码错误");
        }
        adminUser.setPwd(DigestUtils.md5Hex(newPwd));
        adminUserRepository.save(adminUser);

    }

}
